layui.extend({
    admin: '../../js/admin'
});
layui.use(['form','layer','upload','admin'],function(){
    var form = layui.form,
    $ = layui.jquery;
    var layer = parent.layer === undefined ? layui.layer : top.layer,
        upload = layui.upload;

    // 用户分组下拉菜单
    $.ajax({
        url: '/gincms/ajax/getauthgroup',
        dataType: 'json',
        success: function(res){
            var group_id = $('#group_id').attr("data-group_id");
            var data = res.data;
            var dom = '<option value="">选择用户分组</option>';
            for(var i = 0; i < data.length; i++){
                dom += '<option value="'+data[i].id+'" >'+data[i].name+'</option>'
            }
            $('#group_id').html(dom);
            $('#group_id').val(group_id);
            form.render('select');
        }
    });

    //上传头像
    var lastsrc = $("#userFace").attr("src");
    upload.render({
        elem: '.userFaceBtn',
        url: '/gincms/ajax/upload/?type=2&w=200&h=200&lastsrc='+lastsrc,
        method : "post",  //此处是为了演示之用，实际使用中请将此删除，默认用post方式提交
        done: function(res, index, upload){
            if (res.code == 0) {
                $('#userFace').attr('src', res.data.src);
            } else {
                top.layer.msg(res.msg, {icon: 2, time:3000});
            }
        }
    });

    //添加验证规则
    form.verify({
        newPwd : function(value, item){
            if (value.length>0){
                if(value.length < 6){
                    return "密码长度不能小于6位";
                }
            }
        },
        confirmPwd : function(value, item){
            if(!new RegExp($("#newPwd").val()).test(value)){
                return "两次输入密码不一致，请重新输入！";
            }
        }
    });

    //提交个人资料

    form.on("submit(editInfo)",function(data){
        $(this).text("提交中...").attr("disabled","disabled").addClass("layui-disabled");

        var data = {
            username : $(".username").val(),
            nickname : $(".nickname").val(),
            email    : $(".email").val(),
            avatar   : $(".avatar").attr("src"),
            status   : $('.status select').val(),
            group_id : $('#group_id').val()
        };

        var id = $("#id").val();
        var type = 'post';
        if (id>0) {
            type = 'put';
            data = $.extend(data,{id:id});
        }
        var password = $("#newPwd").val();
        if (password!="") {
            data = $.extend(data,{password:password});
        }
        var successfun = function(){
            layer.closeAll("iframe");
            parent.location.reload();
        };
        ZjqAdminAjax('/gincms/admin/save', type, data, successfun);

        $(this).text("立即提交").removeAttr("disabled").removeClass("layui-disabled");
        return false;
    });

});